package com.xxxx.seckill.controller;


import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.xxxx.seckill.pojo.Order;
import com.xxxx.seckill.pojo.SeckillOrder;
import com.xxxx.seckill.pojo.User;
import com.xxxx.seckill.service.IGoodsService;
import com.xxxx.seckill.service.IOrderService;
import com.xxxx.seckill.service.ISeckillOrderService;
import com.xxxx.seckill.vo.GoodsVo;
import com.xxxx.seckill.vo.RespBeanEnum;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;

import java.util.HashMap;
import java.util.Map;


/**
 * 秒杀
 * <p>
 *
 * @author zhoubin
 * @since 1.0.0
 */
@Slf4j
@Controller
@RequestMapping("/seckill")
public class SecKillController {

	@Autowired
	private IGoodsService goodsService;
	@Autowired
	private ISeckillOrderService seckillOrderService;
	@Autowired
	private IOrderService orderService;
	@Autowired
	private RedisTemplate redisTemplate;


	private Map<Long, Boolean> EmptyStockMap = new HashMap<>();

	@PostMapping("/doSeckill")
	public String doSeckill(Model model,
							User user,
							Long goodsId){

		System.out.println("进入到 doSeckill方法了");

		//判断用户是否存在
		if (user == null){

			return "login";
		}

		model.addAttribute("user",user);

		//查询商品
		GoodsVo goods = goodsService.findGoodsVoByGoodsId(goodsId);

		//判断库存
		if (goods.getStockCount() < 1){

			model.addAttribute("errMsg", RespBeanEnum.SECKILL_STOCK_NOT_ENOUGHT);

			//跳转到错误提示页面
			return "seckillFail";
		}

		//判断用户是否提交重复抢购
		QueryWrapper<SeckillOrder> wrapper = new QueryWrapper<>();

		wrapper.eq("user_id",user.getId())
				.eq("goods_id",goodsId);

		SeckillOrder seckillOrder = seckillOrderService.getOne(wrapper);

		if (seckillOrder != null) {

			model.addAttribute("errMsg",RespBeanEnum.REPEAR_SECILL_ORDER);

			return "secKillFail";
		}

		Order order =  orderService.seckillOrder(user,goods);

		model.addAttribute("order",order);
		model.addAttribute("goods",goods);

		return "orderDetail";

	}

}